package rpg.engine.client;

import rpg.client.Instruction;
import rpg.client.model.Facing;
import rpg.client.model.Position;

public final class PositionCalculator {
	private static final double CIRCLE_RADIANS = 2 * Math.PI;

	public static Facing newFacing(final Facing old,
			final Instruction.Type direction) {
		double h = old.getHorizontal();
		if (direction == Instruction.Type.TURN_LEFT) {
			h += (Math.PI / 2);
		} else if (direction == Instruction.Type.TURN_RIGHT) {
			h -= (Math.PI / 2);
		}

		if (h > CIRCLE_RADIANS) {
			h -= CIRCLE_RADIANS;
		}
		if (h < 0) {
			h += CIRCLE_RADIANS;
		}

		return new Facing(h);
	}

	public static Position newPosition(final Position old, final Facing facing,
			final Instruction.Type type) {
		final Facing newFacing = newFacing(facing, type);

		float x1 = old.getX();
		float y1 = old.getY();

		if (type == Instruction.Type.MOVE_FORWARD) {
			x1 = x1 + (float) (Math.cos(facing.getHorizontal()));
			y1 = y1 - (float) (Math.sin(facing.getHorizontal()));
		} else if (type == Instruction.Type.MOVE_NORTH) {
			y1 = y1 - 1;
		} else if (type == Instruction.Type.MOVE_SOUTH) {
			y1 = y1 + 1;
		} else if (type == Instruction.Type.MOVE_WEST) {
			x1 = x1 - 1;
		} else if (type == Instruction.Type.MOVE_EAST) {
			x1 = x1 + 1;
		} else {
		}

		if (x1 < 0) {
			x1 = 0;
		}
		if (y1 < 0) {
			y1 = 0;
		}

		final Position.Builder pb = new Position.Builder();
		pb.map(old.getMapID());
		pb.x(x1);
		pb.y(y1);
		return pb.build();
	}
}
